<script setup>
defineOptions({
  name: 'ChannelEdit',
})
import { articleAddchannel, articleEditChannel } from '@/api/article'
import { ref } from 'vue'
// 定义表单数据
const formModel = ref({
  cate_name: '',
  cate_alias: '',
})
// 定义emit
const emit = defineEmits(['success'])
const visible = ref(false)
const open = (row) => {
  visible.value = true

  console.log(row)
  // 初始化表单数据 如果点击编辑要回显
  formModel.value = { ...row }
}
defineExpose({
  open,
})

const formRef = ref()
const rules = ref({
  cate_name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { parttern: /^\S{1,10}$/, message: '请输入1-10个非空字符', trigger: 'blur' },
  ],
  cate_alias: [
    { required: true, message: '请输入分类别名', trigger: 'blur' },
    { parttern: /^\S{1,15}$/, message: '请输入1-15个非空字符', trigger: 'blur' },
  ],
})

// 添加分类方法
const addChannel = async () => {
  if (formModel.value.id) {
    try {
      await formRef.value.validate()
      await articleEditChannel(formModel.value)
      ElMessage.success('编辑成功')
      visible.value = false
      emit('success') // 通知父组件添加成功
    } catch (error) {
      return
    }
  } else {
    try {
      await formRef.value.validate()
      await articleAddchannel(formModel.value)
      ElMessage.success('添加成功')
      visible.value = false
      emit('success') // 通知父组件添加成功
    } catch (error) {
      return
    }
  }
}
</script>

<template>
  <!-- 如果formModel中有id，则为编辑，否则为添加 -->
  <el-dialog v-model="visible" :title="formModel.id ? '编辑分类' : '添加分类'">
    <el-form
      ref="formRef"
      :model="formModel"
      :rules="rules"
      label-width="100px"
      style="padding-right: 30px"
    >
      <el-form-item label="分类名称" prop="cate_name">
        <el-input v-model="formModel.cate_name" minlength="1" maxlength="10"></el-input>
      </el-form-item>
      <el-form-item label="分类别名" prop="cate_alias">
        <el-input v-model="formModel.cate_alias" minlength="1" maxlength="15"></el-input>
      </el-form-item>
    </el-form>
    <el-button type="primary" @click="addChannel">添加</el-button>
    <el-button @click="visible = false">取消</el-button>
  </el-dialog>
</template>
